package org.dwell.vertx3.demos.tcp;

import io.vertx.core.Vertx;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;

/**
 * Created by JianGuo on 2016/1/15.
 */
public class NetClientTest {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        //Configure a TCP client
        NetClientOptions options = new NetClientOptions().setConnectTimeout(10000);
        //Configure connection attempts
        //设置客户端重连机制，尝试重连10次，每隔500ms重连一次
        options.setReconnectAttempts(10).setReconnectInterval(500);

        //Create a TCP client
        NetClient client = vertx.createNetClient(options);
        //Make a connection
        client.connect(4321, "localhost", res -> {
            if (res.succeeded()) {
                System.out.println("Connected!");
                NetSocket socket = res.result();

                //socket中出现异常会进入这个方法
                socket.exceptionHandler(t -> {
                    t.printStackTrace();
                });

                socket.closeHandler(h -> {
                    System.out.println("connection has been close by server side");
                });

                //Reading data from server side
                socket.handler(h -> {
                    System.out.println("I received some bytes: " + h.length() + ", " + h.toString());
                });

            } else {
                System.out.println("Failed to connect: " + res.cause().getMessage());
            }
        });


    }

}
